/**
 * Created by xz on 2017/6/1.
 */
// var $tbody = $("#sample-table-1 tbody");
jQuery(function ($) {
    $('.date-picker').datepicker({autoclose: true}).next().on(ace.click_event, function () {
        $(this).prev().focus();
    });
});
var allStation = [];
var nowdate = new Date();
var oneweekdate = new Date(nowdate-30*24*3600*1000);
$("#startdate").val(beginDate(oneweekdate));
$("#enddate").val(endDate(nowdate));

function beginDate(date) {
    return endDate(date);
};

function endDate(date) {
    return date.getFullYear() + "-" + ("0" + (date.getMonth() + 1)).slice(-2) + "-" + ("0" + date.getDate()).slice(-2);
};
console.log(1);
// getAllInfo().done(function() {
    // 初始化table
    $("#yuanfen_table").bootstrapTable({
        // 'url': '../serviceType/findAll',
        'url': '/community/forummessage/queryAllForumMsg',
        'toolbar': $('div[data-name="btnCtl"]'),
        'queryParams':queryParams,
        'cache':false,
        'sidePagination': 'server',
        'toolbarAlign': 'right',
        'undefinedText': '-',
        'striped': true,
        'pagination': true,
        'sortable': true, //是否启用排序
        'sortOrder': "asc", //排序方式
        'pageSize': globalPageSize,
        'pageList': [],
        'clickToSelect': true,
        'singleSelect': true,
        'smartDisplay': true,
        'responseHandler': function (resb) {
            return {
                'total': resb.data.total,
                'rows': resb.data.rows
            }
        },
        'onCheck': function() {
            $("button[data-target='#updateModal'], button[data-target='#deleteModal']").removeAttr("disabled");
        },
        'onUncheck': function() {
            $("button[data-target='#updateModal'], button[data-target='#deleteModal']").attr("disabled", 'true');
        },
        'onPageChange': function() {
            if($("#yuanfen_table").bootstrapTable('getSelections')[0]){
                $("#yuanfen_table").bootstrapTable('uncheckBy', {
                    field: 'typeId',
                    values: [$("#yuanfen_table").bootstrapTable('getSelections')[0].typeId]
                });
            }

        },
        'columns': [{
            'checkbox': true,
            // 'class': 'hide'
        },
            {
                'field': 'userId',
                'title': '用户ID',
                'width':100,
                'align': 'center'

            },
            {
                'field': 'msgType',
                'title': '猿粪类型',
                'width':100,
                'align': 'center',
                'formatter': function (msgType) {
                    var obj = {'1':'猿圈','2':'问答'};
                    return obj[msgType];
                }
            },{
                'field': 'msgStruct',
                'title': '消息结构',
                'align': 'center',
                'width':100
            },{
                'field': 'msgContent',
                'title': '猿粪内容',
                'align': 'center'

            },{
                'field': 'lineNo',
                'title': '车次信息',
                'width':150,
                'align': 'center'

            },{
                'field': 'status',
                'title': '状态',
                'width':100,
                'align': 'center',
                'formatter': function (status) {
                    if (status == '4001') {
                        status = '启用';
                    } else if (status == '4002') {
                        status = '停用';
                    }
                    ;
                    return status === null ? '未知' : status;
                }
            },{
                'field': 'likesCount',
                'title': '点赞个数',
                'width':100,
                'align': 'center'

            },{
                'field': 'msgDelete',
                'title': '是否删除',
                'width':100,
                'align': 'center'
            },{
                'field': 'createDate',
                'title': '创建日期',
                'width':150,
                'align': 'center',
                'sortable': true
            }

        ]
    });
// });

//请求服务数据时所传参数
function queryParams(params){
    return {
        limit : params.limit, //每一页的数据行数，默认是上面设置的10(pageSize)
        offset : params.offset/params.limit+1 //当前页面,默认是上面设置的1(pageNumber)
    }
}

/**
 * 猿粪查询ajax
 * @param name 请求查询的服务人员名称
 */
function serviceQuery(name) {
    if(($("#inputStation").val()== '')){
        $('#yuanfen_table').bootstrapTable('refreshOptions',{pageNumber:1,pageSize:globalPageSize});
    }else{
        $.ajaxSetup({cache:false});
        $.ajax({
            type: "POST",
            url: "../serviceType/findServiceByName",
            data: {
                "name": name
            },
            dataType: 'json',
            success: function(resb) {
                if (resb.data.length != 0) {
                    $("#yuanfen_table").bootstrapTable('load', resb.data);
                } else {
                    $("#yuanfen_table").bootstrapTable('removeAll');
                }
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                alert(textStatus);
            }
        });
    }
    return false;
}




/**
 * 列表操作(新增，更新，删除)
 * @param action [add/update/remove]
 * @param data
 *               [add/update 数据结构 {name: string, description: string, listAuthorityId: array} ]
 *               [delete 数据结构 {roleId: int}]
 * @param async/scync [default async]
 */
function yuanfengManagement(action, data, async) {
    var url = null;
    (async === false) ? async = false: async = true;
    if (action === 'add') {
        url = '/community/forummessage/saveForumMsg';
    } else {
        url = '/community/forummessage/deleteForumMsg';
    };
    return $.ajax({
        type: "POST",
        url: url,
        data: JSON.stringify(data),
        contentType: "application/json",
        dataType: 'json',
        async: async,
        success: function(resb) {
            alert(resb.message);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            // console.log(XMLHttpRequest, textStatus, errorThrown);
            alert(textStatus);
        }
    });
}

$(document).on('click','.spanIcons',function(){
    $('#inputStation').val("");
    if($('#inputStation').val() ==""){
        $('.spanIcons').removeClass('glyphicon glyphicon-remove');
    }
});
$("#inputStation").keyup(function(){
    if($('#inputStation').val() !=""){
        $('.spanIcons').addClass('glyphicon glyphicon-remove');
    }
    if($('#inputStation').val() ==""){
        $('.spanIcons').removeClass('glyphicon glyphicon-remove');
    }
})

/*
 * 查询所有车站
 */
// function getAllInfo(){
//     return $.ajax({
//         type: "POST",
//         url:'/community/forummessage/queryAllForumMsg?rows=3&currentPage=1',
//         dataType: 'json',
//         error: function(request) {
//             console.log(3);
//             alert(request);
//         },
//         success: function(rs) {
//             console.log(2);
//             if(rs.success){
//                 for(var i = 0;i<rs.data.length;i++){
//                     $(".selectAllStation").append("<option value="+rs.data[i].stationId+">"+rs.data[i].stationName+"</option>");
//                 };
//                 allStation = rs;
//             };
//         }
//     });
// };


/**
 * 查询表单提交
 */
$("#dataSearch").on('click',function() {

    return serviceQuery($("#inputStation").val());
});

//$("#stationFormId").submit(function() {
//    return serviceQueryByStationId($("#serviceProviderSel").val());
//});

/**
 * 新增模态框显示
 */
$("#addModal").on('show.bs.modal', function() {
    $(this).find("input[type=text]").val("");
});

/**
 * 删除模态框显示
 */
$("#deleteModal").on('show.bs.modal', function() {
    var name = $("#yuanfen_table").bootstrapTable('getSelections')[0].name,
        html = '是否删除?';
    $(this).find('div.modal-body').empty().append(html);
});

/**
 * 更新模态框显示
 */

$("#updateModal").on('show.bs.modal', function() {
    var $that = $(this),
        $inputs = $that.find("input[type=text]"),

        tableData = $("#yuanfen_table").bootstrapTable("getSelections")[0],
        roleAuth = {};


    var $status = $(this).find('select[name="status"]');


    // 设置ID,姓名,帐号,电话,年龄
    $inputs[0].value = tableData.typeId;
    $inputs[1].value = tableData.name;
    $inputs[2].value = tableData.introduction;
    $inputs[3].value = tableData.distributionCosts;
    $status.val(tableData.status);



});

/**
 * 新增,更新,删除角色表单提交
 */
$("button[name=submit]").on('click',function() {
    var type = $(this).data("type"),
        $modal = $("#" + type + "Modal"),
        $inputs = $modal.find('input[type="text"]'),


        //$checkboxs = $(this).find('input[type="checkbox"]').prop('checked',true),
        tableData = $("#yuanfen_table").bootstrapTable("getSelections")[0],
        data = null,
        $that = $(this);


    // 模式选择,设置不同的data和url
    if (type === 'delete') {
        data = {
            'forumMsgId': tableData.forumMsgId
        };
    } else if (type === 'add') {
        var obj = jQuery("#addForm").validationEngine('validate', {promptPosition : "centerRight", autoPositionUpdate : true});
        if(!obj){
            return false;
        };
        var $status = $modal.find('select[name="status"]');
        var $orderNo = $modal.find('select[name="orderNo"]');
        data = {

            "forumMsgId": null,
            "userId": "123",
            "userType": "123",
            "msgType": "123",
            "msgStruct": "游玩",
            "userLongitude": null,
            "userLatitude": null,
            "postionLabel": "G6013-长沙南",
            "msgDelete": 0,
            "reportCount": 0,
            "prohibit": 0,
            "heat": 0,
            "lineNo": "G6013",
            "trainDate": null,
            "picUrl": "123",
            "createDate": null,
            "likesCount": 10,
            "aboardStation": "长沙南",
            "arrivedStation": "深圳北",
            "commentCount": 10,
            "msgContent": "天气真好"

        };
    } else if (type ==='update') {
        var $status = $modal.find('select[name="status"]');

        data = {
            'typeId':$inputs[0].value,
            'name':$inputs[1].value,
            'introduction': $inputs[2].value,
            'distributionCosts': $inputs[3].value,
            'status':$status.val()

        };
        data['typeId'] = tableData.typeId;
    };


    $modal.modal('hide');
    // 完成ajax后刷新表格数据
    yuanfengManagement(type, data).done(function() {
        $("#yuanfen_table").bootstrapTable("refresh");
        $("button[data-target='#updateModal'], button[data-target='#deleteModal']").attr("disabled", 'true');
        // $that[0].reset();
    });

    // 阻止表格冒泡事件
    return false;
});
